//
//  TF_TextView.swift
//  TalkfunSDKDemo
//
//  Created by 莫瑞权 on 2022/5/21.
//  Copyright © 2022 Talkfun. All rights reserved.
//

import UIKit

class TF_TextView: UITextView {
//    var  verificationCode:Bool = false
    /// 占位文字
   @objc public  var tf_placeholder: String?
    {
        didSet{
            if( tf_placeholder != nil)
            {
                self.setNeedsDisplay()
            }
        }
    }
    /// 占位文字颜色
  @objc public var tf_placeholderColor: UIColor? = UIColor.lightGray
    
   @objc public var tf_placeholderX: CGFloat = 5
    {
        didSet{
            
                self.setNeedsDisplay()
            
        }
    }
   @objc public var tf_placeholderY: CGFloat = 8
    {
        didSet{
            
                self.setNeedsDisplay()
            
        }
    }
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)

        // 设置默认字体
        self.font = UIFont.systemFont(ofSize: 15)
        NotificationCenter.default.addObserver(self, selector: #selector(textDidChange(_:)), name: UITextView.textDidChangeNotification, object: nil)
       
    }
    deinit {
           NotificationCenter.default.removeObserver(self)
       }
       
       required init?(coder aDecoder: NSCoder) {
           fatalError("init(coder:) has not been implemented")
       }
       
       override func draw(_ rect: CGRect) {
           // 如果有文字,就直接返回,不需要画占位文字
           if self.text != nil {
               if self.text.count>0 {
                   return
               }
              
           }
           
           // 属性
           let attrs: [NSAttributedString.Key : Any] = [NSAttributedString.Key.foregroundColor: self.tf_placeholderColor as Any, NSAttributedString.Key.font: self.font!]
           
           // 文字
           var rect1 = rect
           rect1.origin.x = tf_placeholderX
           rect1.origin.y = tf_placeholderY
           rect1.size.width = rect1.size.width - 2*rect1.origin.x
           if(tf_placeholder != nil)
           {
               (self.tf_placeholder! as NSString).draw(in: rect1, withAttributes: attrs)
           }
           
       }
       
       @objc func textDidChange(_ note: Notification) {
           // 会重新调用drawRect:方法
           self.setNeedsDisplay()
       }
}
